﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Trajectory2D : MonoBehaviour {

    readonly float timeToCompare = 0.01f;
    float timeElapse = 0;
    float timeTotal = 0;

    public float velocity = 30;
    public float angle = 45;
    public float gravity = -1;

    private float vx;
    private float vy;

	void Start () {
        //初始化的两个方向的速度
        vx = velocity * Mathf.Cos(Mathf.Deg2Rad * angle);
        vy = velocity * Mathf.Sin(Mathf.Deg2Rad * angle);
        Debug.Log(string.Format("两个方向的速度：{0}, {1}", vx, vy));
    }

    private void Update()
    {
        timeElapse += Time.deltaTime;
        timeTotal += Time.deltaTime;

        if (timeToCompare < timeElapse)
        {
            //计算当前帧两个分量上面的速度
            timeElapse = 0;

            float vxx = vx;
            float vyy = vy + gravity * timeTotal;

            Debug.Log(string.Format("当前速度：{0}, {1}", vxx, vyy));

            //根据当前的速度得到新的位置
            Vector2 position = Vector2.zero;
            position.x = transform.position.x + vxx * Time.deltaTime;
            position.y = transform.position.y + vyy * Time.deltaTime;

            transform.position = position;

            //显示曲线
            GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            sphere.transform.position = position;
            sphere.transform.localScale = new Vector3(0.2f, 0.2f, 0.2f);
            sphere.GetComponent<Renderer>().material.color = Color.red;
        }

    }

}
